package com.sound.ampache;

/* Copyright (c) 2010 Brian Kirkman <kirkman.brian@gmail.com>
*
* +------------------------------------------------------------------------+
* | This program is free software; you can redistribute it and/or          |
* | modify it under the terms of the GNU General Public License            |
* | as published by the Free Software Foundation; either version 3         |
* | of the License, or (at your option) any later version.                 |
* |                                                                        |
* | This program is distributed in the hope that it will be useful,        |
* | but WITHOUT ANY WARRANTY; without even the implied warranty of         |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          |
* | GNU General Public License for more details.                           |
* |                                                                        |
* | You should have received a copy of the GNU General Public License      |
* | along with this program; if not, write to the Free Software            |
* | Foundation, Inc., 59 Temple Place - Suite 330,                         |
* | Boston, MA  02111-1307, USA.                                           |
* +------------------------------------------------------------------------+
*
* Special thanks to the following: 
* Kevin Purdy, author of Amdroid, for much of the code used in this project
* 
* Jorge Ramon, author of MiamiCoder blog, for many great BlackBerry examples
* published on his blog.
* 
* 
*/

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.WLANInfo;

/**
 * Some static utility methods which may be useful for applications which 
 * make HTTP connections. 
 */
public class TransportUtils {
	
	
    // Whether or not to the simulator should use MDS to connect.
    // By default this should be false, however if you are testing
    // in an environment where MDS will be the expected connection method,
    // set this to true to have the simulator attempt to use MDS.  This variable
    // has no effect on what happens on a real device.
    private static final boolean USE_MDS_IN_SIMULATOR = false;
    
    
    /**
     * true if the device is able to send and receive <bold>data</bold>
     * @return   <code>true</code> if the handheld can make http connections;
     *           <code>false</code> otherwise.
     */
    public static boolean isInCoverage(){
        
        int service = RadioInfo.getNetworkService();
        if ((service & RadioInfo.NETWORK_SERVICE_DATA) == RadioInfo.NETWORK_SERVICE_DATA){
            int level = RadioInfo.getSignalLevel();
            if (level != RadioInfo.LEVEL_NO_COVERAGE){
                return true;
            }
        }
        return false;        
    }    
    
    
    public static String getConnectionString() {
    	String connString = null; 
    	String connType = DataStore.getConnType();
    	
    	if (connType == "Auto") {
    		connString = connAuto();
    	} else if (connType == "WiFi") {
    		connString = connWiFi();
    	} else if (connType == "Carrier") {
    		connString = connCarrier();
    	} else if (connType == "BES-MDS") {
    		connString = connBES();
    	} else if (connType == "Device") {
    		connString = "";
    	}
    	
    	return connString;
    }
    
    
    /**
     * Determines what connection type to use and returns the necessary string to use it.
     * @return A string with the connection info
     */
    public static String connAuto()
    {
        // This code is based on the connection code developed by Mike Nelson of AccelGolf.
        // http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection        
        String connString = null;                
                        
        // Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR variable.
        if(DeviceInfo.isSimulator())
        {
            if(TransportUtils.USE_MDS_IN_SIMULATOR)
            {
                    connString = ";deviceside=false";                 
            }
            else
            {
                    connString = ";deviceside=true";
            }
        }                                        
                
        // Wifi is the preferred transmission method
        else if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
        {
            connString = connWiFi();
        }
                        
        // Is the carrier network the only way to connect?
        else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
        {               
        	connString = connCarrier();
        }                
        
        // Check for an MDS connection instead (BlackBerry Enterprise Server)
        else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
        {
            connString = connBES();
        }
        
        // If there is no connection available abort to avoid bugging the user unnecssarily.
        else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
        {
            connString = "";
        }
        
        // In theory, all bases are covered so this shouldn't be reachable.
        else
        {
            connString = ";deviceside=true";
        }        
        
        return connString;
    }
    
    
    private static String connWiFi() {
    	return ";interface=wifi";
    }
    
    
    private static String connBES() {
    	return ";deviceside=false";
    }
    
    
    private static String connCarrier()
    {
        ServiceRecord[] records = ServiceBook.getSB().getRecords();
        int currentRecord;
        String carrierUid = null;
        
        for(currentRecord = 0; currentRecord < records.length; currentRecord++)
        {
            if(records[currentRecord].getCid().toLowerCase().equals("ippp"))
            {
                if(records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0)
                {
                	carrierUid = records[currentRecord].getUid();
                }
            }
        }

        if(carrierUid == null) 
        {
            // Has carrier coverage, but not BIBS.  So use the carrier's TCP network
            return ";deviceside=true";
        }
        else 
        {
            // otherwise, use the Uid to construct a valid carrier BIBS request
            return ";deviceside=false;connectionUID=" + carrierUid + ";ConnectionType=mds-public";
        }
    } 
    
    
}
